import uuid
from datetime import datetime
from typing import Optional, List
import math

from pydantic import BaseModel
from .file import UploadedFileInDB
from app.schemas.base import BaseSchema


# Message Schemas
class MessageBase(BaseModel):
    role: str
    content: str
    reasoning_content: Optional[str] = None
    file_ids: Optional[List[uuid.UUID]] = None


class MessageCreate(MessageBase):
    conversation_id: uuid.UUID


class MessageInDB(BaseSchema):
    id: uuid.UUID
    conversation_id: uuid.UUID
    role: str
    content: str
    reasoning_content: Optional[str] = None
    file_ids: Optional[List[uuid.UUID]] = None
    created_at: datetime
    files: Optional[List[UploadedFileInDB]] = []

    model_config = {"from_attributes": True}


# Conversation Schemas
class ConversationBase(BaseModel):
    title: str


class ConversationCreate(ConversationBase):
    user_id: uuid.UUID


class ConversationInDB(BaseSchema):
    id: uuid.UUID
    user_id: uuid.UUID
    title: str
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class ConversationWithMessages(ConversationInDB):
    messages: List[MessageInDB] = []


# API Request/Response Schemas
class ChatRequest(BaseModel):
    message: str
    conversation_id: Optional[uuid.UUID] = None
    file_ids: Optional[List[uuid.UUID]] = None
    thinkingMode: bool = False


class ConversationListItem(BaseSchema):
    """对话列表项"""
    id: uuid.UUID
    user_id: uuid.UUID
    title: str
    created_at: datetime
    updated_at: datetime
    message_count: int = 0  # 消息数量


class ConversationListResponse(BaseModel):
    """对话列表分页响应"""
    items: List[ConversationListItem]
    total: int
    page: int
    page_size: int
    total_pages: int


class ConversationWithMessagesPaginated(BaseSchema):
    """对话详情和分页消息列表"""
    # 对话信息
    id: uuid.UUID
    user_id: uuid.UUID
    title: str
    created_at: datetime
    updated_at: datetime

    # 分页消息
    messages: List[MessageInDB]
    total: int
    page: int
    page_size: int
    total_pages: int
